package com.atguigu.grainmall.product.service.impl;

import com.atguigu.grainmall.product.service.CategoryBrandRelationService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.grainmall.product.dao.BrandDao;
import com.atguigu.grainmall.product.entity.BrandEntity;
import com.atguigu.grainmall.product.service.BrandService;
import org.springframework.transaction.annotation.Transactional;


@Service("brandService")
public class BrandServiceImpl extends ServiceImpl<BrandDao, BrandEntity> implements BrandService {

    @Autowired
    CategoryBrandRelationService categoryBrandRelationService;

    /**
     * 分类列表+模糊检索
     * @param params
     * @return
     */
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        // 获取模糊查询条件
        String key = (String) params.get("key");
        LambdaQueryWrapper<BrandEntity> wrapper = new LambdaQueryWrapper<>();
        // 判断是否需要模糊查询
        if(!key.isEmpty()){
            wrapper.eq(BrandEntity::getBrandId,key).or().like(BrandEntity::getName,key);
        }
        IPage<BrandEntity> page = this.page(
                new Query<BrandEntity>().getPage(params),
                wrapper
        );
        return new PageUtils(page);
    }

    /**
     * 修改
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateDatil(BrandEntity brand) {
        // 保证冗余字段的数据一致
        this.updateById(brand);
        // 判断此次更新是否更新了 品牌名
        if(!brand.getName().isEmpty()){
            // 有直接将关联表中的品牌名一起修改掉
            categoryBrandRelationService.updateBrand(brand.getBrandId(),brand.getName());
            // todo 更新其他关联
        }
    }

}
